import React, { useState, useEffect } from 'react';
import { ColumnsType } from 'antd/es/table';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { SettingOutlined } from '@ant-design/icons';
import { Card, Space, Button, Table, Modal, Checkbox, Typography, Drawer } from 'antd';
import request from '@/utils/request';
import MRPSearch from './MRPSearch';
import MRPRun from './MRPRun';
import moment from 'moment';
import { FormattedMessage, useIntl } from 'umi';
import SuggComp from '../purchase/components/suggComp';

const { Text } = Typography;
interface User {
  orderNum: number;
  orderLine: number;
  partNum: string;
  partDescription: string;
  revisionNum: string;
  requireQty: number;
  supplyQty: number;
  sugQty: number;
  onhandQty: number;
  poQty: number;
  jobQty: number;
  inspQty: number;
  dmrQty: number;
  nonConfQty: number;
  ium: string;
  jobNum: string;
  assemblySeq: number;
  jobSeq: number;
  opCode: string;
  opDesc: string;
  dueDate: Date;
  isPrep: boolean;
  id: string;
}
const ViewPage: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [skipCount, setSkipCount] = useState(0);
  const [maxResultCount] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [params, setParams] = useState({});
  const [visible3, setVisible3] = useState(false);
  const [partNum, setPartNum] = useState<string>('');

  const intl = useIntl();

  useEffect(() => {
    query();
  }, [skipCount, maxResultCount, params]);

  const query = () => {
    setLoading(true);
    request('/api/services/app/MRPDetail/GetList', {
      method: 'GET',
      params: {
        skipCount,
        maxResultCount,
        ...params,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          setTotalCount(response.result.totalCount);
          setDataSource(response.result.items);
        }
      }
      setLoading(false);
    });
  };

  const handleSearch = (values: any) => {
    setParams(values);
    setSkipCount(0);
  };

  const columns: ColumnsType<User> = [
    {
      title: intl.formatMessage({ id: 'pages.productCode' }),
      dataIndex: 'partNum',
      fixed: 'left',
    },
    {
      title: intl.formatMessage({ id: 'pages.description' }),
      dataIndex: 'partDescription',
      ellipsis: true,
      width: 50,
      fixed: 'left',
    },
    {
      title: intl.formatMessage({ id: 'pages.workOrderNumber' }),
      render: (record: any) =>
        (record.jobNum ? record.jobNum : '0') + '-' + record.assemblySeq + '-' + record.jobSeq,
    },
    {
      title: intl.formatMessage({ id: 'pages.requiredQuantity' }),
      dataIndex: 'requireQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.supplyQuantity' }),
      dataIndex: 'supplyQty',
      render: (text: any, record: any) => (
        <Text strong type={record.supplyQty < record.requireQty ? 'danger' : 'success'}>
          {text}
        </Text>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.dueDate' }),
      dataIndex: 'dueDate',
      render: (text: any) => <span>{text ? moment(text).format('YYYY-MM-DD') : text}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.onHandQuantity' }),
      dataIndex: 'onhandQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.purchase' }),
      dataIndex: 'poQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.suggestion' }),
      dataIndex: 'sugQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.workOrder' }),
      dataIndex: 'jobQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.inspection' }),
      dataIndex: 'inspQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.dmr' }),
      dataIndex: 'dmrQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.nonConforming' }),
      dataIndex: 'nonConfQty',
    },
    {
      title: intl.formatMessage({ id: 'pages.orderNumber' }),
      render: (record: any) =>
        record.orderNum + '-' + record.orderLine + '-' + record.orderRelNum,
    },
    {
      title: intl.formatMessage({ id: 'pages.requirementNumber' }),
      dataIndex: 'reqNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.isPrepared' }),
      dataIndex: 'isPrep',
      render: (text: boolean) => <Checkbox checked={text} />,
      fixed: 'right',
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card
        title={intl.formatMessage({ id: 'pages.materialRequirementsPlanning' })}
        extra={
          <Space id="S1">
            <MRPSearch onSearch={handleSearch}></MRPSearch>
            <Button
              type="primary"
              danger
              onClick={() => setVisible(true)}
              icon={<SettingOutlined />}
            >
              <span><FormattedMessage id="pages.runMRP" /></span>
            </Button>
          </Space>
        }
      >
        
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          scroll={{ x: 'max-content' }}
          pagination={{
            onChange: (page) => {
              setSkipCount((page - 1) * maxResultCount);
            },
            pageSize: maxResultCount,
            total: totalCount,
            showTotal: (total) => `${intl.formatMessage({ id: 'pages.total' })} ${total} ${intl.formatMessage({ id: 'pages.items' })}`,
          }}
          onRow={(record) => {
            return {
              onDoubleClick: () => {
                setPartNum(record.partNum);
                setVisible3(true);
              },
            };
          }}
        />
      </Card>
      <Modal
        width={800}
        title={intl.formatMessage({ id: 'pages.runMRP' })}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => setVisible(false)}
        footer={false}
      >
        <MRPRun />
      </Modal>
      <Drawer
        title={<FormattedMessage id="pages.poSuggest" />}
        placement="right"
        closable={true}
        visible={visible3}
        onClose={() => setVisible3(false)}
        getContainer={false}
        mask={true}
        maskClosable={true}
        destroyOnClose
        width={1200}
      >
        <SuggComp partNum={partNum} />
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default ViewPage;
